package engine;

/**
 * Class for determining word weights
 * 
 * @author ak2765
 * @author Vika
 *
 */
final class WordWeightCalculator {
	
	private static final double LAPLACE = 0.001;

	private static final double STOP_WORD_WEIGHT = .001;

	private final InvertedWordList invertedWordList;

	public WordWeightCalculator(InvertedWordList invertedWordList) {
		super();
		this.invertedWordList = invertedWordList;
	}

	/**
	 * @param word
	 * @return
	 */
	public double calculateWeight(String word) {
		if (WekaStopwordsList.isStopword(word)) {
			return STOP_WORD_WEIGHT;	
		}
		
		if (isNumber(word)) {
			return STOP_WORD_WEIGHT;
		}
		
		double positiveNegativeTitleRatio = this.calculatePostiveNegativeTitleRatio(word);
		
		double positiveNegativeDescriptionRatio = this.calculatePositiveNegativeDescriptionRatio(word);

		return (positiveNegativeTitleRatio * 2) + (positiveNegativeDescriptionRatio);
	}

	/**
	 * @param word
	 * @return
	 */
	private boolean isNumber(String word) {
		try {
			Double.parseDouble(word);
		} catch (NumberFormatException ex) {
			return false;
		}
		return true;
	}

	/**
	 * @param word
	 * @return
	 */
	double calculatePositiveNegativeDescriptionRatio(String word) {
		return calculateRatio(this.invertedWordList.getPositiveDescriptionFrequencies(word), invertedWordList.getNegativeDescriptionFrequencies(word));
	}
	
	/**
	 * @param word
	 * @return
	 */
	double calculatePostiveNegativeTitleRatio(String word) {
		return calculateRatio(this.invertedWordList.getPositiveTitleFrequencies(word), this.invertedWordList.getNegativeTitleFrequencies(word));
	}

	/**
	 * @param positiveFrequencies
	 * @param negativeFrequencies
	 * @return
	 */
	private double calculateRatio(int positiveFrequencies, int negativeFrequencies) {
		if (negativeFrequencies == 0) {
			return (double)positiveFrequencies / LAPLACE;	
		}
		
		return (double)positiveFrequencies / (double)negativeFrequencies;
	}


}
